package com.itheima.netcore;


import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;


/**
 * 提供网络操作的类
 */
public class HMChatManager
{
    private String TAG = "HMChatManager";
    private static HMChatManager instance;

    private HMChatManager()
    {

    }

    public static HMChatManager getInstance()
    {
        if (instance == null)
        {
            synchronized (HMChatManager.class)
            {
                if (instance == null)
                {
                    instance = new HMChatManager();
                }
            }
        }
        return instance;
    }

    public void send(String url,
                     //请求消息头
                     Map<String, String> headers,
                     // 请求参数
                     Map<String, String> parameters,
                     final HMObjectCallback callback)
    {
        HttpUtils utils = new HttpUtils();
        // url
        RequestParams params = new RequestParams();
        // 请求消息头
        if (headers != null)
        {
            for (Map.Entry<String, String> me : headers.entrySet())
            {
                params.addHeader(me.getKey(),
                                 me.getValue());
            }
        }

        // 请求参数
        if (parameters != null)
        {
            for (Map.Entry<String, String> me : parameters.entrySet())
            {
                params.addBodyParameter(me.getKey(),
                                        me.getValue());
            }
        }

        //发送网络请求
        utils.send(HttpRequest.HttpMethod.POST,
                   url,
                   params,
                   new RequestCallBack<String>()
                   {

                       @Override
                       public void onSuccess(ResponseInfo<String> stringResponseInfo)
                       {
                           String result = stringResponseInfo.result;
                           //成功
                           Log.d(TAG,
                                 "访问网络成功 : " + result);
                           // 解析 TODO:
                           //解析对象
                           JsonParser parser = new JsonParser();
                           //
                           JsonElement root = parser.parse(result);
                           JsonObject rootObject = root.getAsJsonObject();

                           //获取flag节点
                           JsonPrimitive flagJson = rootObject.getAsJsonPrimitive("flag");
                           boolean flag = flagJson.getAsBoolean();


                           if (callback == null)
                           {
                               return;
                           }

                           if (flag)
                           {
                               //访问接口成功
                               JsonObject dataJson = rootObject.getAsJsonObject("data");

                               // 将json的对象变为 bean
                               Gson gson = new Gson();

                               ParameterizedType type = (ParameterizedType) callback.getClass()
                                                                                    .getGenericInterfaces()[0];
                               Type classType = type.getActualTypeArguments()[0];

                               Object data = gson.fromJson(dataJson,
                                                           classType);
                               callback.onSuccess(data);
                           } else
                           {
                               //访问接口失败 TODO:
                               int errorCode = rootObject.getAsJsonPrimitive("errorCode")
                                                         .getAsInt();
                               String errorString = rootObject.getAsJsonPrimitive("errorString")
                                                              .getAsString();
                               callback.onFailure(errorCode,
                                                  errorString);
                           }
                       }
                       @Override
                       public void onFailure(HttpException e,
                                             String s)
                       {
                           //失败
                           Log.d(TAG,
                                 "访问网络失败 : " + s);

                           if (callback != null)
                           {
                               callback.onFailure(HMError.CODE_NET_CONNECT,
                                                  HMError.STRING_NET_CONNET);
                           }

                       }
                   });
    }
}
